//
//  SentencePlayVC.swift
//  Game
//
//  Created by woniu on 2025/9/3.
//

import Foundation

import UIKit
import SnapKit
import AVFoundation

class SentencePlayVC: BaseVC {
    public var gameModel:GameModel!
    //配置
    private var config = SentenceConfig()

    // UI 组件
    private var sentenceCard:UIView!
    private var sentenceLabel:UILabel!
    private var optionsContainer: UIView!
    private var optionCards: [UIView] = []
    private var optionLabels: [UILabel] = []
    private var dragOriginFrames: [CGRect] = []
    private var audioPlayer: AVAudioPlayer?
    // 底部控制按钮
    private let prevButton = UIButton(type: .system)
    private let selectButton = UIButton(type: .system)
    private let clearButton = UIButton(type: .system)
    private let nextButton = UIButton(type: .system)
    private var playSoundButton = UIButton(type: .custom)

    // 拖拽相关
    private var draggingCard: UIView?
    private var draggingLabel: UILabel?
    private var dragStartPoint: CGPoint = .zero
    private var dragCardIndex: Int = -1
    private var allGameList:[GameModel] = []
    private var resultImgView:UIImageView!
    private var imgeView:UIImageView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //查询出所有数据，根据时间排序，用于上一个，下一个
        allGameList = GameManager.share.getAllGamesBy(type: .sentence)
        update(game: self.gameModel)
        createBottomView()
    }
    
    //更新模型并更新页面组件
    public func update(game:GameModel){
        self.gameModel = game
        let dic = game.jsonData.toDic()
        self.config = SentenceConfig.deserialize(from: dic) ?? SentenceConfig()
        
        createTopView()
    }

    private func createTopView() {
        view.backgroundColor = .black
        sentenceCard?.removeFromSuperview()
        sentenceLabel?.removeFromSuperview()
        optionsContainer?.removeFromSuperview()
        imgeView?.removeFromSuperview()
        optionCards.forEach {$0.removeFromSuperview()}
        optionLabels.forEach {$0.removeFromSuperview()}
        optionCards.removeAll()
        optionLabels.removeAll()
        playSoundButton.removeFromSuperview()
       
        
        let iconImage = GameManager.share.getImageBy(config.imageName)
        
        // 句子卡片
        sentenceCard = UIView()
        sentenceCard.backgroundColor = UIColor(white: 0.12, alpha: 0.9)
        sentenceCard.layer.cornerRadius = 18
        sentenceCard.layer.shadowColor = UIColor.white.cgColor
        sentenceCard.layer.shadowOpacity = 0.08
        sentenceCard.layer.shadowRadius = 10
        sentenceCard.layer.shadowOffset = CGSize(width: 0, height: 4)
        view.insertSubview(sentenceCard, at: 0)
        sentenceCard.snp.makeConstraints { make in
            //没有图片则上面空多一点，有图片则空闲少一点，多留点空隙在底部显示图片
            let topSpace:CGFloat = iconImage == nil ? 100 : 20
            make.top.equalTo(self.backButton.snp.bottom).offset(topSpace)
            make.left.equalToSuperview().offset(20)
            make.right.equalToSuperview().offset(-20)
            make.height.equalTo(110)
        }

        // 句子文本
        sentenceLabel = UILabel()
        sentenceLabel.text = config.getRenderedSentence()
        sentenceLabel.font = UIFont.systemFont(ofSize: 32, weight: .bold)
        sentenceLabel.textColor = Colors.yellow
        sentenceLabel.textAlignment = .center
        sentenceLabel.numberOfLines = 0
        sentenceCard.addSubview(sentenceLabel)
        sentenceLabel.snp.makeConstraints { make in
            make.edges.equalToSuperview().inset(16)
        }
        
        playSoundButton = UIButton(type: .custom)
        playSoundButton.imageView?.contentMode = .scaleAspectFit
        playSoundButton.setImage(UIImage(named: "播放语音"), for: .normal)
        playSoundButton.addTarget(self, action: #selector(onPlaySound), for:.touchUpInside)
        sentenceCard.addSubview(playSoundButton)
        playSoundButton.snp.makeConstraints { make in
            make.right.equalToSuperview().offset(-3)
            make.bottom.equalToSuperview().offset(-3)
            make.size.equalTo(CGSize(width: 30, height: 30))
        }

        // 答案卡片区域（普通 UIView，手动布局）
        optionsContainer = UIView()
        view.insertSubview(optionsContainer, at: 0)
        optionsContainer.snp.makeConstraints { make in
            make.top.equalTo(sentenceCard.snp.bottom).offset(40)
            make.left.right.equalTo(sentenceCard)
            make.height.equalTo(80)
        }

        let cardColors: [UIColor] = [.systemPink, .systemBlue, .systemGreen, .yellow]
        let textColors: [UIColor] = [.white, .white, .white, .black]
        let fontSizes: [CGFloat] = [24, 24, 24, 24]
        let optionTitles = ["A", "B", "C", "D"]
        let cardCount = config.options.count
        let cardWidth: CGFloat = ((UIScreen.main.bounds.width - 40 - CGFloat((cardCount-1)*24)) / CGFloat(cardCount))
        let cardHeight: CGFloat = 80
        for i in 0..<cardCount {
            let card = UIView()
            card.backgroundColor = cardColors[i % cardColors.count]
            card.layer.cornerRadius = 18
            card.layer.shadowColor = UIColor.black.cgColor
            card.layer.shadowOpacity = 0.12
            card.layer.shadowRadius = 6
            card.layer.shadowOffset = CGSize(width: 0, height: 3)
            card.isUserInteractionEnabled = true
            card.tag = i
            optionsContainer.addSubview(card)
            // 手动布局（相对于 optionsContainer）
            let origin = CGPoint(x: CGFloat(i)*(cardWidth+24), y: 0)
            card.frame = CGRect(origin: origin, size: CGSize(width: cardWidth, height: cardHeight))

            let label = UILabel()
            label.text = "\(optionTitles[i])  \(config.options[i])"
            label.textColor = textColors[i % textColors.count]
            label.font = UIFont.boldSystemFont(ofSize: fontSizes[i % fontSizes.count])
            label.textAlignment = .center
            label.numberOfLines = 1
            card.addSubview(label)
            label.frame = CGRect(x: 8, y: 8, width: cardWidth-16, height: cardHeight-16)

            let pan = UIPanGestureRecognizer(target: self, action: #selector(handleCardPan(_:)))
            card.addGestureRecognizer(pan)

            optionCards.append(card)
            optionLabels.append(label)
        }

        // 记录初始frame（相对于 optionsContainer）
        dragOriginFrames = optionCards.map { $0.frame }
        
        //图片
        imgeView = UIImageView()
        imgeView.contentMode = .scaleAspectFit
        self.view.insertSubview(imgeView, at: 0)
        imgeView.image = iconImage
        imgeView.isHidden = iconImage == nil
        imgeView.snp.makeConstraints { make in
            make.top.equalTo(optionsContainer.snp.bottom).offset(50)
            make.left.right.equalToSuperview()
            make.bottom.equalToSuperview().offset(-130)
        }
        
    }

    //构建底部组件
    public func createBottomView(){
        
        // 底部控制栏（上一个 / 选择 / 下一个）
        let bottomBar = UIView()
        bottomBar.backgroundColor = UIColor(white: 0.06, alpha: 0.6)
        bottomBar.layer.cornerRadius = 12
        view.addSubview(bottomBar)
        bottomBar.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(20)
            make.right.equalToSuperview().offset(-20)
            make.bottom.equalTo(view.safeAreaLayoutGuide.snp.bottom).offset(-12)
            make.height.equalTo(56)
        }

        // 按钮样式
        prevButton.setTitle(" Last", for: .normal)
        prevButton.setImage(UIImage(systemName: "chevron.left"), for: .normal)
        prevButton.tintColor = .white
        prevButton.backgroundColor = UIColor(white: 0.12, alpha: 1)
        prevButton.layer.cornerRadius = 10
        prevButton.addTarget(self, action: #selector(onPrevTapped), for: .touchUpInside)

        selectButton.setTitle(" Choice", for: .normal)
        selectButton.setImage(UIImage(systemName: "filemenu.and.selection"), for: .normal)
        selectButton.tintColor = .white
        selectButton.backgroundColor = UIColor(white: 0.12, alpha: 1)
        selectButton.layer.cornerRadius = 10
        selectButton.addTarget(self, action: #selector(onSelectTapped), for: .touchUpInside)
        
        clearButton.setTitle(" Clear", for: .normal)
        clearButton.setImage(UIImage(systemName: "xmark.circle"), for: .normal)
        clearButton.tintColor = .white
        clearButton.backgroundColor = UIColor(white: 0.12, alpha: 1)
        clearButton.layer.cornerRadius = 10
        clearButton.addTarget(self, action: #selector(onClear), for: .touchUpInside)

        nextButton.setTitle(" Next", for: .normal)
        nextButton.setImage(UIImage(systemName: "chevron.right"), for: .normal)
        nextButton.tintColor = .white
        nextButton.backgroundColor = UIColor(white: 0.12, alpha: 1)
        nextButton.layer.cornerRadius = 10
        nextButton.addTarget(self, action: #selector(onNextTapped), for: .touchUpInside)

        bottomBar.addSubview(prevButton)
        bottomBar.addSubview(selectButton)
        bottomBar.addSubview(clearButton)
        bottomBar.addSubview(nextButton)

        prevButton.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(12)
            make.centerY.equalToSuperview()
            make.width.equalTo(96)
            make.height.equalTo(40)
        }
        selectButton.snp.makeConstraints { make in
            make.centerX.equalToSuperview().offset(-80)
            make.centerY.equalToSuperview()
            make.width.equalTo(120)
            make.height.equalTo(44)
        }
        
        clearButton.snp.makeConstraints { make in
            make.centerX.equalToSuperview().offset(80)
            make.centerY.equalToSuperview()
            make.width.equalTo(120)
            make.height.equalTo(44)
        }
        
        nextButton.snp.makeConstraints { make in
            make.right.equalToSuperview().offset(-12)
            make.centerY.equalToSuperview()
            make.width.equalTo(96)
            make.height.equalTo(40)
        }

        resultImgView = UIImageView()
        resultImgView.isHidden = true
        resultImgView.layer.cornerRadius = 10
        resultImgView.layer.masksToBounds = true
        
//        self.view.addSubview(resultImgView)
//        resultImgView.snp.makeConstraints { make in
//            make.size.equalTo(CGSize(width: 400, height: 400))
//            make.center.equalToSuperview()
//        }
    }
    
    // MARK: - 拖拽手势
    @objc private func handleCardPan(_ gesture: UIPanGestureRecognizer) {
        guard let card = gesture.view, let idx = optionCards.firstIndex(of: card) else { return }
        // 使用 window 作为统一坐标系
        guard let window = view.window, let optionsContainer = self.optionsContainer else { return }
        let translation = gesture.translation(in: window)
        switch gesture.state {
        case .began:
            draggingCard = card
            draggingLabel = optionLabels[idx]
            // 记录初始中心点（将卡片转到 window 坐标系后更新）
            dragCardIndex = idx
            // 提升到window层级
            let cardFrameInWindow = card.convert(card.bounds, to: window)
            card.frame = cardFrameInWindow
            window.addSubview(card)
            // 更新起始点（window坐标）
            dragStartPoint = card.center
        case .changed:
            // 在 window 坐标系中移动
            card.center = CGPoint(x: dragStartPoint.x + translation.x, y: dragStartPoint.y + translation.y)
            // 判断拖拽卡片中心点是否进入句子卡片区域（window 坐标）
            let cardCenterInWindow = card.center
            let sentenceFrameInWindow = sentenceCard.convert(sentenceCard.bounds, to: window)
            if sentenceFrameInWindow.contains(cardCenterInWindow) {
                sentenceCard.layer.borderWidth = 4
                sentenceCard.layer.borderColor = UIColor.systemBlue.cgColor
            } else {
                sentenceCard.layer.borderWidth = 0
            }
        case .ended, .cancelled:
            // 拖拽结束，判断中心点是否在句子卡片区域
            sentenceCard.layer.borderWidth = 0
            let cardCenterInWindow = card.center
            let sentenceFrameInWindow = sentenceCard.convert(sentenceCard.bounds, to: window)
            
            // 无论是否正确，卡片都动画回原位：将目标初始 frame 转换到 window，然后动画到该 frame，完成后把视图加入回 optionsContainer 并设置为原始 frame
            let targetFrameInWindow = optionsContainer.convert(dragOriginFrames[idx], to: window)
            UIView.animate(withDuration: 0.35, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.5, options: [], animations: {
                card.frame = targetFrameInWindow
            }, completion: { _ in
                // 恢复到原父视图
                card.removeFromSuperview()
                card.frame = self.dragOriginFrames[idx]
                optionsContainer.insertSubview(card, at: 0)
                
                // 检查答案
                if sentenceFrameInWindow.contains(cardCenterInWindow) {
                    let answer = self.config.options[idx]
                    if answer == self.config.correctAnswer {
                        self.showResult(isCorrect: true)
                        self.fillBlankWithAnswer(answer)
                    } else {
                        self.showResult(isCorrect: false)
                    }
                }
            })
            draggingCard = nil
            draggingLabel = nil
            dragCardIndex = -1
        default:
            break
        }
    }

    // MARK: - 结果反馈
    private func showResult(isCorrect: Bool) {
        resultImgView.isHidden = false
        
        resultImgView.removeFromSuperview()
        self.view.addSubview(resultImgView)
        resultImgView.snp.remakeConstraints { make in
            make.size.equalTo(CGSize(width: 400, height: 400))
            make.center.equalToSuperview()
        }
        
        if isCorrect == false{
            Utils.playErrorSound()
            resultImgView.image = UIImage(named: "错误")
            
        }else{
            Utils.playSuccessSound()
            resultImgView.image = UIImage(named: "正确")
        }
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+1) {
            self.resultImgView.isHidden = true
        }
    }

    // 填入并高亮显示答案
    private func fillBlankWithAnswer(_ answer: String) {
        let raw = config.sentence
        let blank = config.blankWord
        let replaced = raw.replacingOccurrences(of: "\\b" + NSRegularExpression.escapedPattern(for: blank) + "\\b", with: answer, options: .regularExpression)
        let attr = NSMutableAttributedString(string: replaced)
        let nsRange = (replaced as NSString).range(of: answer, options: .caseInsensitive)
        if nsRange.location != NSNotFound {
            attr.addAttribute(.foregroundColor, value: Colors.green, range: nsRange)
            attr.addAttribute(.font, value: UIFont.systemFont(ofSize: 32, weight: .heavy), range: nsRange)
        }
        sentenceLabel.attributedText = attr
        sentenceLabel.backgroundColor = UIColor(white: 0.18, alpha: 1)
        sentenceLabel.layer.cornerRadius = 12
        sentenceLabel.layer.masksToBounds = true
    }
    
    //上一个
    @objc func onPrevTapped(){
        
        var preItem:GameModel?
        for(index,item ) in allGameList.enumerated(){
            if item.key == gameModel.key && index > 0{
                preItem = allGameList[index-1]
                break
            }
        }
        guard let preGame = preItem else{
            Utils.alert(msg: "没有更多了")
            return
        }
        self.update(game: preGame)
    }
    
    //选择
    @objc func onSelectTapped(){
        //先选择类型，再根据类型配置页面
        let typeAlert = SingleTablePicker(frame: .zero)
        let titles:[String] = allGameList.map{$0.name}
        
        typeAlert.onSelectedRowBlock = {[weak self](index,val)in
            guard let `self` = self else { return }
            let game = self.allGameList[index]
            self.update(game: game)
        }
        typeAlert.show(dataArray: titles, pickerW: 500,defaultSelectRowTitle: gameModel.name)
    }
    
    //清除
    @objc func onClear(){
        self.update(game: self.gameModel)
    }
    
    //下一个
    @objc func onNextTapped(){
        var nextItem:GameModel?
        let totalCount = allGameList.count
        for(index,item ) in allGameList.enumerated(){
            if item.key == gameModel.key && (index+1) < totalCount{
                nextItem = allGameList[index+1]
                break
            }
        }
        guard let nextGame = nextItem else{
            Utils.alert(msg: "没有更多了")
            return
        }
        self.update(game: nextGame)
    }
    
    //播放语音
    @objc func onPlaySound(){
        if Utils.isEnableSound == false{
            ToastView.show("已禁用语言，在首页左上角设置")
            return
        }
        let sentence = config.sentence
        Utils.play(sentence:sentence)
    }
}
